package com.seven.webhook.component.prometheus;

import cn.hutool.http.*;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.seven.webhook.model.bean.alertmanager.Alerts;
import lombok.extern.log4j.Log4j2;

import java.util.HashMap;
import java.util.List;

@Log4j2
public class PrometheusApiUtils {
    /**
     * 获取数据
     * todo 对象化
     */
    public static String getInfo() {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("query", "100 - (avg(rate(node_cpu_seconds_total{mode=\"idle\"}[2m])) * 100) > 0.71");
        paramMap.put("start", "1604897365.194");
        paramMap.put("end", "1604900965.194");
        paramMap.put("step", "14");
        String s = HttpUtil.get("http://10.202.80.60:9090/api/v1/query_range", paramMap);
        System.out.println(s);
        return null;
    }

    /**
     * 激活规则
     */
    public static void activeRule() {
        String post = HttpUtil.post("http://10.202.80.60:9090/-/reload", "");
        System.out.println(post);
    }

    /**
     * 获取告警列表
     */
    public static List<Alerts> getAlertList() {
        String get = HttpUtil.get("http://10.202.80.60:9090/api/v1/alerts");
        JSONObject jsonObject = JSONUtil.parseObj(get);
        List<Alerts> data = jsonObject.getJSONObject("data")
                .getJSONArray("alerts").toList(Alerts.class);
        return data;
    }

    private static void checkHttpResult(String result) {
        if (result.contains("code")) {
            // TODO: 2020/11/11 正则获取message信息
            /**
             * {
             *   "code": 601,
             *   "message": "silenceID in path must be of type uuid: \"e0ddedfd-37ab-44bb-8b0f-dd3a4c154e4\""
             * }
             */
            log.error(result);
            throw new RuntimeException("message");
        }
    }
}
